package com.kitty.game.role.service;

import com.kitty.common.mysql.DataSource;
import com.kitty.common.mysql.DataSourceType;
import com.kitty.common.mysql.TargetDataSource;
import com.kitty.game.fuling.model.Fuling;
import com.kitty.game.hunqiao.model.HunQiaoData;
import com.kitty.game.role.model.AccountLogin;
import com.kitty.game.role.model.Role;
import com.kitty.game.welfare.model.CommonFetchedData;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service
public class KuafuService {
    Logger logger = LoggerFactory.getLogger(KuafuService.class);

    @Autowired
    Dao dao;
    @Autowired
    JdbcTemplate jdbcTemplate;

    @DataSource(value= DataSourceType.KUAFU)
    public AccountLogin queryAccount(String id){
        AccountLogin account = dao.fetch(AccountLogin.class, Cnd.where("id", "=", id));
        return account;
    }

    @DataSource(value= DataSourceType.KUAFU)
    public void insert(Role role){
        role.doBeforeSave();
        dao.insertOrUpdate(role);
    }

    @DataSource(value= DataSourceType.KUAFU)
    public void insertFuling(Fuling fuling){
        fuling.doBeforeSave();
        dao.insertOrUpdate(fuling);
    }

    @DataSource(value= DataSourceType.KUAFU)
    public void insertHunqiao(HunQiaoData hunQiaoData){
        dao.insertOrUpdate(hunQiaoData);
    }
    @DataSource(value= DataSourceType.KUAFU)
    public List<String> fetch(String sid){
        Sql sql = Sqls.create("select name from t_role where sid=@sid");
        sql.setParam("sid",sid);
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection connection, ResultSet resultSet, Sql sql) throws SQLException {
                ArrayList<String> arrayList = new ArrayList<>();
                while (resultSet.next()){
                    arrayList.add(resultSet.getString("name"));
                }
                return arrayList;
            }
        });
        dao.execute(sql);
        return sql.getList(String.class);
    }

    @DataSource(value= DataSourceType.KUAFU)
    public CommonFetchedData fetchData(String type){
        CommonFetchedData commonFetchedData = dao.fetch(CommonFetchedData.class,Cnd.where("type","=",type));
        return commonFetchedData;
    }
}
